package net.tensor.skynet.adapter

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import net.tensor.skynet.R
import net.tensor.skynet.actity.ItemDetailActivity
import net.tensor.skynet.common.user.entity.User
import net.tensor.skynet.entity.DataContainer
import net.tensor.skynet.fragment.ItemDetailFragment

class SkynetAdapter : RecyclerView.Adapter<SkynetAdapter.OneViewHolder>() {
    private var onClickListener: View.OnClickListener

    init {
        onClickListener = View.OnClickListener { v ->
            val item = v.tag as User
            val intent = Intent(v.context, ItemDetailActivity::class.java).apply {
                putExtra(ItemDetailFragment.ARG_ITEM_ID, item.id)
            }
            v.context.startActivity(intent)
        }
    }

    fun replaceAll(list: java.util.ArrayList<User>) {
        DataContainer.USER_ITEMS.clear()
        if (list.size > 0) {
            DataContainer.USER_ITEMS.addAll(list)
        }
        notifyDataSetChanged()
    }

    /**
     * 插入数据使用notifyItemInserted，如果要使用插入动画，必须使用notifyItemInserted
     * 才会有效果。即便不需要使用插入动画，也建议使用notifyItemInserted方式添加数据，
     * 不然容易出现闪动和间距错乱的问题
     */
    fun addData(position: Int, list: java.util.ArrayList<User>) {
        DataContainer.USER_ITEMS.addAll(position, list)
        notifyItemInserted(position)
    }

    //移除数据使用notifyItemRemoved
    fun removeData(position: Int) {
        DataContainer.USER_ITEMS.removeAt(position)
        notifyItemRemoved(position)
    }

    open class BaseViewHolder(itemView: View?) :
        RecyclerView.ViewHolder(itemView!!) {
        open fun setData(data: Any?, position: Int) {}
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OneViewHolder {
        return OneViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(
                    R.layout.item_list_content,
                    parent,
                    false
                )
        )
    }

    override fun getItemCount(): Int {
        return DataContainer.USER_ITEMS.size
    }

    override fun onBindViewHolder(holder: OneViewHolder, position: Int) {
        val item = DataContainer.USER_ITEMS[position]
        holder.idView.text = item.id
        holder.contentView.text = item.name
        with(holder.itemCard) {
            tag = item
            setOnClickListener(onClickListener)
        }
    }

    class OneViewHolder(view: View) : BaseViewHolder(view) {

        val idView: TextView = view.findViewById(R.id.id_text)
        val contentView: TextView = view.findViewById(R.id.content)
        val itemCard: CardView = view.findViewById(R.id.itemCard)

    }
}